import 'package:flutter/material.dart';
import 'package:package_info_plus/package_info_plus.dart';

import 'apk_utils.dart';
import 'download_dialog.dart';

class UpdaterPage extends StatefulWidget {
  const UpdaterPage({super.key});

  @override
  State<UpdaterPage> createState() => _UpdaterPageState();
}

class _UpdaterPageState extends State<UpdaterPage> {
  final String apiUrl = "https://example.com/api/update"; // 替换为实际 API

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("App 更新")),
      body: Center(
        child: ElevatedButton(
          onPressed: _checkUpdate,
          child: const Text("检查更新"),
        ),
      ),
    );
  }

  void _checkUpdate() async {
    final updateInfo = await ApkUtils.checkForUpdate(apiUrl);
    if (updateInfo != null) {
      final serverVersionCode = int.parse(updateInfo['versionCode']);
      final downloadUrl = updateInfo['url'];
      final checksum = updateInfo['checksum'];

      // 获取当前版本号
      PackageInfo packageInfo = await PackageInfo.fromPlatform();
      int currentVersionCode = int.parse(packageInfo.version);

      if (serverVersionCode > currentVersionCode) {
        _showUpdateDialog(downloadUrl, checksum);
      } else {
        _showSnackBar("当前已是最新版本！");
      }
    } else {
      _showSnackBar("检查更新失败，请稍后重试！");
    }
  }

  void _showUpdateDialog(String downloadUrl, String checksum) {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => DownloadDialog(
        title: "发现新版本",
        message: "正在下载更新，请稍候...",
        onDownload: () async {
          final filePath =
              await ApkUtils.downloadApk(downloadUrl, "latest.apk", (progress) {
            debugPrint("下载进度：${(progress * 100).toStringAsFixed(0)}%");
          });
          if (filePath != null &&
              await ApkUtils.validateFile(filePath, checksum)) {
            ApkUtils.installApk(filePath);
          }
        },
      ),
    );
  }

  void _showSnackBar(String message) {
    ScaffoldMessenger.of(context)
        .showSnackBar(SnackBar(content: Text(message)));
  }
}
